package com.example.event.customer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.constant.MqConstants;
import com.example.dto.OrderCreateDTO;
import com.example.event.BaseEvent;
import com.example.service.OrderService;
import com.example.service.SkuService;
import com.example.service.UserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class OrderCloseConsumer {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserCouponService userCouponService;

    @Autowired
    private SkuService skuService;

    @RabbitListener(queues = MqConstants.Queue.ORDER_DELAY_QUEUE)
    public void listener(String message) {
        try {
            log.info("监听订单关闭信息: {}", message);
            // 转换对象
            BaseEvent.EventMessage<List<OrderCreateDTO>> eventMessage =
                    JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<List<OrderCreateDTO>>>() {}.getType());

            List<OrderCreateDTO> orders = eventMessage.getData();
            orderService.closeOrder(orders);
            userCouponService.updateCouponStatusToUnUsed(orders);
            skuService.unlockStock(orders);
        } catch (Exception e) {
            log.error("订单关闭信息处理失败: {}", message, e);
        }
    }
}
